package com.ditri.distrident.common.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * @date: 2020-08-06 15:07
 * @author: edxuanlen
 * @version: 1.0
 **/
@Configuration
public class RedisConfig {

//    private RedisConnectionFactory redisConnectionFactory = null;

//    @Bean
//    public RedisConnectionFactory initRedisConnectionFactory() {
//        if (this.redisConnectionFactory != null) {
//            return redisConnectionFactory;
//        }
//        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
//        redisStandaloneConfiguration.setHostName("120.79.224.142");
//        redisStandaloneConfiguration.setPassword(RedisPassword.of("000000"));
//        redisStandaloneConfiguration.setPort(6379);
//        redisStandaloneConfiguration.setRe
//        JedisPoolConfig poolConfig = new JedisPoolConfig();
//        //最大空闲数
//        poolConfig.setMaxIdle(30);
//        //最大连接数
//        poolConfig.setMaxTotal(50);
//        //最大等待毫秒
//        poolConfig.setMaxWaitMillis(2000);
//        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().poolConfig(poolConfig).build();
//        //创建Jedis连接工厂
//        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
//        //获取单机的Redis配置
//        this.redisConnectionFactory = jedisConnectionFactory;
//        return jedisConnectionFactory;
//    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 将刚才的redis连接工厂设置到模板类中
        template.setConnectionFactory(redisConnectionFactory);
        // 设置key的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化器
        //使用Jackson 2，将对象序列化为JSON
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //json转对象类，不设置默认的会将json转成hashmap
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }
}
